/**
 * Copyright 2011 Joe Choi, All rights reserved.
 */
package tec.data.persistence.jdbc;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import tao.data.persistence.Query;
import tao.data.persistence.Session;
import tao.data.structure.Iterator;
import tec.data.persistence.PersistenceException;
import tec.data.structure.ListControl;

/**
 * @author Joe Choi
 */
public class JDBCSession implements Session {
	public JDBCSession(Connection connection) {
		if(connection == null) throw new IllegalArgumentException("Session: connection may not be null!");
		try { 
			this.connection = connection;
			this.connection.setAutoCommit(false);
		} catch (SQLException e) { 
			throw new PersistenceException(e);
		}
		querys = new ListControl<Query>();
	}
	
	@Override
	public Query query() {
		Statement stmt;		
		try {
			stmt = connection.createStatement();
		} catch (SQLException e) {
			throw new PersistenceException(e);
		}
		Query q = new SqlQuery(stmt);
		querys.add(q);
		return(q);
	}
	
	@Override
	public void close() {
		Iterator<Query> it = querys.getList().iterate();
		try {
			while(it.hasNext()) it.next().close();
			if(connection != null && (! connection.isClosed())) connection.close();
		} catch (SQLException e) {
			throw new PersistenceException(e);
		}
	}
	
	private Connection connection;
	private ListControl<Query> querys;
}
